package com.gouwudai.gobbs.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;

import com.gouwudai.gobbs.dao.ITopicBuyDAO;
import com.gouwudai.gobbs.dao.IUserDAO;
import com.gouwudai.gobbs.pojo.TbbsTopicBuy;
import com.gouwudai.gobbs.pojo.TbbsUserInfo;
import com.gouwudai.gobbs.service.ITopicBuyService;
import com.litt.core.exception.BusiException;
import com.litt.core.exception.DBException;
import com.litt.core.util.ParamUtils;

public class TopicBuyServiceImpl implements ITopicBuyService
{
	ITopicBuyDAO topicBuyDAO;
	IUserDAO userDAO;
	
	/**
	 * 新增或更新购买
	 * @param paramMap
	 * @return
	 */
	public void doBuyTopic(HashMap paramMap) throws BusiException
	{	
			int topicId = ParamUtils.getMapToInt(paramMap, "topicId");
			int userId = ParamUtils.getMapToInt(paramMap, "userId");
			BigDecimal topicTypeNum = ParamUtils.getMapToBigDecimal(paramMap, "topicTypeNum");	//购买帖子所需金币
			
			TbbsTopicBuy tbbsTopicBuy = topicBuyDAO.loadByTopicUser(topicId,userId);			
			if(tbbsTopicBuy==null)	//新增
			{	
				//读取用户信息
				
				TbbsUserInfo tbbsUserInfo= userDAO.load(userId);
				if(tbbsUserInfo.getUserMoney().subtract(topicTypeNum).doubleValue()<0)
				{
					throw new DBException("您的金币不足!");
				}				
				tbbsTopicBuy = new TbbsTopicBuy();
				tbbsTopicBuy.setTopicId(topicId);
				tbbsTopicBuy.setTopicTypeNum(topicTypeNum);
				tbbsTopicBuy.setUserId(userId);
				tbbsTopicBuy.setPayMoney(topicTypeNum);
				tbbsTopicBuy.setAddDatetime(new Date());				
				topicBuyDAO.save(tbbsTopicBuy);
				//扣除用户相应金币
				userDAO.topicBuyUpdate(userId,topicTypeNum);
			}	
	}	

	public TbbsTopicBuy load(Integer id)
	{
		return (TbbsTopicBuy)topicBuyDAO.load(id);
	}
	
    /**
     * 根据主题ID和用户ID查找
     * @param topicId
     * @param userId
     * @return
     */
	public TbbsTopicBuy loadByTopicUser(Integer topicId,Integer userId)
	{
		return (TbbsTopicBuy)topicBuyDAO.loadByTopicUser(topicId, userId);
	}

	public void setTopicBuyDAO(ITopicBuyDAO topicBuyDAO) {
		this.topicBuyDAO = topicBuyDAO;
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}
}